//
//  RoomSelectionViewController.m
//  mUBB
//
//  Created by Cosmin Stirbu on 3/8/13.
//  Copyright (c) 2013 Cosmin Stirbu. All rights reserved.
//

#import "RoomSelectionViewController.h"
#import "RoomsManager.h"
#import "Room.h"
#import "ListWrapper.h"
#import "WSError.h"
#import "Constants.h"

@interface RoomSelectionViewController ()

@end

@implementation RoomSelectionViewController

@synthesize roomsTableView;

- (id)initWithNibName:(NSString *)nibNameOrNil booking:(Booking *)booking
{
    self = [super initWithNibName:nibNameOrNil bundle:nil];
    if (self) {
        // Custom initialization
        
        _booking = booking;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    // Get Rooms
    [Utils showLoadingOn:self];
    [[RoomsManager instance] getRoomsForFaculty:_booking.course.faculty delegate:self];
}

#pragma mark - TableView Data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [_sortedBuildingNames count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSString *buildingName = [_sortedBuildingNames objectAtIndex:section];
    return [[_groupedRooms objectForKey:buildingName] count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return [_sortedBuildingNames objectAtIndex:section];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"Cell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    NSString *buildingName = [_sortedBuildingNames objectAtIndex:indexPath.section];
    Room *room = [[_groupedRooms objectForKey:buildingName] objectAtIndex:indexPath.row];
    cell.textLabel.text = room.name;
    
    // Checkmark
    if (_booking.room.roomId == room.roomId) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    } else {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    return cell;
}


#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    NSString *buildingName = [_sortedBuildingNames objectAtIndex:indexPath.section];
    Room *room = [[_groupedRooms objectForKey:buildingName] objectAtIndex:indexPath.row];
    
    _booking.room = room;
    
    [tableView reloadData];
    
}


#pragma mark - Rooms Protocol

- (void)didReceiveRoomsWithSuccess:(id)object forTicket:(Ticket *)ticket {
    [Utils hideLoadingOn:self];
    if (!_isOnScreen)
        return;
    ListWrapper *rooms = (ListWrapper *)object;
    _groupedRooms = [[RoomsManager instance] groupRoomsByBuildings:rooms.itemsList];
    _sortedBuildingNames = [[_groupedRooms allKeys] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
    [roomsTableView reloadData];
}

- (void)didReceiveRoomsWithFailure:(id)object forTicket:(Ticket *)ticket {
    [Utils hideLoadingOn:self];
    if (!_isOnScreen)
        return;
    WSError *error = (WSError *)object;
    if (error.errorCode == StatusCodeConnectionError) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:error.errorMessage delegate:self cancelButtonTitle:NSLocalizedString(@"ALERT_CANCEL", nil) otherButtonTitles:NSLocalizedString(@"ALERT_RETRY", nil), nil];
        [alertView show];
    } else {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:error.errorMessage delegate:nil cancelButtonTitle:NSLocalizedString(@"ALERT_OK", nil) otherButtonTitles: nil];
        [alertView show];
    }
}



#pragma mark - Alert View Delegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex != alertView.cancelButtonIndex) {
        // Get Rooms
        [Utils showLoadingOn:self];
        [[RoomsManager instance] getRoomsForFaculty:_booking.course.faculty delegate:self];
    }
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidUnload {
    [self setRoomsTableView:nil];
    [super viewDidUnload];
}
@end
